<?php
/**
 * Created by PhpStorm.
 * User: heqian
 * Date: 17-4-21
 * Time: 下午9:40
 */
require_once 'App.php';
$app = new \Swoole\App();
$app->http_server->on('request', function ($request, $response) use ($app) {
    if (isset($request->get['action']) && $request->get['action'] == 'demo') {
        ob_start();
        require __DIR__ . '/demo.html';
        $content = ob_get_clean();
        $response->end($content);

    } else if (isset($request->get['type']) && $request->get['type'] == 'publish') {

        $msg = 'send fail';
        foreach ($app->http_server->connections as $fd) {
            $connect_info = $app->http_server->connection_info($fd);
            if (isset($connect_info['uid']) && $connect_info['uid'] == $request->get['to']) {
                $content = isset($request->get['content']) ? $request->get['content'] : '';
                $app->http_server->push($fd, json_encode(['cmd' => 'new_msg', 'info' => $content]));
                $msg = 'send success';
                break;
            } else if ($request->get['to'] == '') {
                $content = isset($request->get['content']) ? $request->get['content'] : '';
                $app->http_server->push($fd, json_encode(['cmd' => 'new_msg', 'info' => $content]));
                $msg = 'send success';
            }
        }
        $response->end($msg);
    }

});
$app->http_server->on('open', function (swoole_websocket_server $server, $request) {
    $server->push($request->fd, json_encode(['cmd' => 'login', 'info' => 'login success']));
    echo "server: handshake success with fd{$request->fd}\n";
});

$app->http_server->on('message', function (swoole_websocket_server $server, $frame) {
    $req = json_decode($frame->data);
    var_dump($server->bind($frame->fd, $req->uid));
    var_dump($server->connection_info($frame->fd));
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, json_encode(['cmd' => 'new_msg', 'info' => 'login success']));
});

$app->http_server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$app->run();